<?php

class Label extends DBObject {

    public $table = 'mtl.labels';
    const table_static = 'mtl.labels';
    public $sequence = 'mtl.labels_id';
    const sequence_static = 'mtl.labels_id';

    public static function getById($id) {

        return parent::getById($id, __CLASS__);
    }

    public static function getByName($name) {

       return parent::getByName($name, __CLASS__);
    }

    public function load() {

        parent::load();

        $res = $this->dbo->getRow("SELECT
            name
            FROM $this->table
            WHERE id=?",
            array(
                DBInteger::create($this->id)
            ));

        throwOnError($res);

        if(empty($res))
            throw new Exception(_('Failed to load label.'));

        $this->name = DBString::create($res['name']);

        return true;
    }

    public function loadByName() {

        parent::loadByName();

        $res = $this->dbo->getOne("SELECT
            id
            FROM $this->table
            WHERE LOWER(name)=LOWER(?)",
            array(
                DBString::create($this->name)
            ));

        throwOnError($res);

        if(empty($res))
            throw new Exception(_('Failed to load label.'));

        $this->id = DBInteger::create($res);

        return true;
    }

    public function __set($name, $value) {
        
        $value = trim($value);

        // validation
        switch($name) {
            case 'name':
                if(strlen($value) > MAX_LABEL_NAME_LENGTH)
                    throw new Exception(_('Label name can be ').MAX_LABEL_NAME_LENGTH._(' characters max.'));

                break;
        }

        parent::__set($name, $value);
    }

    public function __get($name) {

        return parent::__get($name);
    }

    public function save() {

        //if(!$this->changed && $this->loaded)
        //    return true;

        if(!is_null($this->id)) {

            $res = $this->dbo->query("UPDATE $this->table SET
                name=?
                WHERE id=?",
                array(
                    DBString::create($this->name),
                    DBInteger::create($this->id)
                ));

            throwOnError($res);

            if($res != DB_OK)
                throw new Exception(_('Failed to save label.'));

        } else {

            parent::save(__CLASS__);
        }

        return $this->id;
    }

    public static function create($name) {

        return parent::create($name, __CLASS__);
    }

    public static function exists($name) {

        return parent::exists($name, __CLASS__);
    }

}